package com.magicode.screen.settingutil;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.magicode.screen.AppContext;
import com.magicode.screen.api.remote.MgcApi;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 版本更新
 */
public class VersionUtil {

    private String newVersionName;
    private boolean isUpdate;
    private Context context;
    private ReactInstanceManager mReactInstanceManager = null;
    public VersionUtil(Context context){
        this.context=context;
    }
    private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) {
        reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName, params);
    }
    public Map getNewVersion(){
        //向服务器发请求获取服务器最新的版本号
        MgcApi.getVersion(mHandler,getVersionName(context));
        Map map=new HashMap();
        map.put("isUpdate",isUpdate);
        map.put("newVersionCode",newVersionName);
        return map;
    }
    private final AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                Map result = mapper.readValue(arg2, HashMap.class);
                String status = (String) result.get("status");
                if ("99".equals(status)) {
                    Map entity= (Map) result.get("entity");
                    if(null!=entity){
                        isUpdate= (boolean) entity.get("isUpdate");
                        if(isUpdate){
                            newVersionName= (String) entity.get("newVersion");
                        }
                        ReactNativeHost rnh = AppContext.getInstance().getReactNativeHost();
                        if (null != rnh) {
                            mReactInstanceManager = rnh.getReactInstanceManager();
                        }
                        WritableMap params = Arguments.createMap();
                        params.putBoolean("isUpdate",isUpdate);
                        params.putString("newVersionCode",newVersionName);
                        sendEvent(mReactInstanceManager.getCurrentReactContext(), "updateVersion", params);

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                onFailure(arg0, arg1, arg2, e);
            }
        }

        @Override
        public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
        }
    };
    public void versionqqdownloader() {
        if (isAvilible(context, "com.tencent.android.qqdownloader")) {// 市场存在
            launchAppDetail(context, "com.magicode.screen", "com.tencent.android.qqdownloader");
        }else if(isAvilible(context, "com.xiaomi.market")) {
            launchAppDetail(context, "com.magicode.screen", "com.xiaomi.market");
        }else if(isAvilible(context, "com.huawei.appmarket")){
            launchAppDetail(context, "com.magicode.screen", "com.huawei.appmarket");
        }
        else {
            Uri uri = Uri.parse("http://a.app.qq.com/o/simple.jsp?pkgname=com.magicode.screen");
            Intent it = new Intent(Intent.ACTION_VIEW, uri);
            context.startActivity(it);
        }
    }
    /**
     * 启动到app详情界面
     *
     * @param appPkg
     *            App的包名
     * @param marketPkg
     *            应用商店包名 ,如果为""则由系统弹出应用商店列表供用户选择,否则调转到目标市场的应用详情界面，某些应用商店可能会失败
     */
    public static void launchAppDetail(Context context, String appPkg, String marketPkg) {
        try {
            if (TextUtils.isEmpty(appPkg))
                return;
            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(uri);
            if (!TextUtils.isEmpty(marketPkg))
                intent.setPackage(marketPkg);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 判断市场是否存在的方法
    public static boolean isAvilible(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        List<String> pName = new ArrayList<String>();// 用于存储所有已安装程序的包名
        // 从pinfo中将包名字逐一取出，压入pName list中
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                pName.add(pn);
            }
        }
        return pName.contains(packageName);// 判断pName中是否有目标程序的包名，有TRUE，没有FALSE
    }


    /**
     * 2 * 获取版本号 3 * @return 当前应用的版本号 4
     * versionCode就应该是整形
     */
    public static int getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            int versioncode = info.versionCode;
            return versioncode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
    /**
     * versionName  1.0.0
     */
    public static String getVersionName(Context context) {
        String versionName="";
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            versionName = info.versionName;
  //          int versioncode = info.versionCode;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }
    /**
     * 包名
     com.tencent.android.qqdownloader 腾讯应用宝
     com.qihoo.appstore 360手机助手
     com.baidu.appsearch 百度手机助手
     com.xiaomi.market 小米应用商店
     com.huawei.appmarket 华为应用商店
     com.wandoujia.phoenix2 豌豆荚
     com.dragon.android.pandaspace 91手机助手
     com.hiapk.marketpho 安智应用商店
     com.yingyonghui.market 应用汇
     com.tencent.qqpimsecure QQ手机管家
     com.mappn.gfan 机锋应用市场
     com.pp.assistant PP手机助手
     com.oppo.market OPPO应用商店
     cn.goapk.market GO市场
     zte.com.market 中兴应用商店
     com.yulong.android.coolmart 宇龙Coolpad应用商店
     com.lenovo.leos.appstore 联想应用商店
     com.coolapk.market cool市场
     */
}
